#!/bin/bash
#功能: 使用jstat展示java进程内存情况
#$1: flag, 获取java进程方式; 0 - 输入进程id; 1 - 输入进程关键词使用ps搜索pid
#$2: name, 进程id或进程关键词
#注: jstat需环境变量PATH中包含${JAVA_HOME}/bin, 
#    若没有定义JAVA_HOME(环境变量PATH中没有java安装目录), 
#    本shell定义java_path="/usr/java/jdk1.7.0_71", 并将${java_path}/bin放入PATH环境变量中
#    如果您的并没有定义JAVA_HOME且java安装路径也不是"/usr/java/jdk1.7.0_71"
#    必须要修改后文中的java_path为应用服务器java安装目录

java_path="/usr/java/jdk1.7.0_71"
if [[ "${JAVA_HOME}" = "" ]]; then
	export PATH=${java_path}/bin:$PATH
fi

#定义日志级别
LOG_LEVEL_ERR=0
LOG_LEVEL_INFO=1
LOG_LEVEL_DEBUG=2

#日志级别小于或等于${log_level}的将被打印。 若使用ERR打印, 将输出重定向至错误输出
log_level=${LOG_LEVEL_INFO}
echopar ()
{
	if [ $1 -gt $log_level ]; then
		return 0
	fi
	
	if [ $1 -eq $LOG_LEVEL_ERR ]; then
		echo "$2" >&2
	else
		echo "$2"
	fi
}

echodebug()
{
	echopar $LOG_LEVEL_DEBUG "[DEBUG]: $1"
}

echoinfo()
{
	echopar $LOG_LEVEL_INFO "[INFO]: $1"
}

echoerr()
{
	echopar $LOG_LEVEL_ERR "[ERROR]: $1"
}

print_err() 
{
	echoinfo "parameter: flag, 获取java进程方式; 0 - 输入进程id; 1 - 输入进程关键词使用ps搜索pid"
	echoinfo "parameter: name, 进程id或进程关键词"
	echoerr "参数输入错误" 
	
	return 0
}

is_suc() 
{
	if [ $? -eq 0 ]; then
		echodebug "command $1 is success"
		return 0
	else
		echoinfo ""
		echoerr "command $1 is failed!!!"
		exit 1
	fi
}

#----------------------------------------------------------
#$1: input  par: pid
#$2: output par: jvm info;
get_thread_info()
{
	local info
	local pid=$1
	local __resultvar=$2
	local tmp=""
	local ret=""
	
	info=$(jstack -l ${pid})
	is_suc "CURLINE[$LINENO], jstack -l ${pid}"
	
	ret=$(echo "$info" |awk '/ tid=0x/ && / nid=0x/ && /runnable/ {print $0}' |wc -l)
	is_suc "CURLINE[$LINENO], get runnable threads"
	tmp=$(echo "runnableThreads=${ret}")
	
	ret=$(echo "$info" |awk '/ tid=0x/ && / nid=0x/ {print $0}' |wc -l)
	is_suc "CURLINE[$LINENO], get total threads"
	tmp=$(echo "${tmp},totalThreads=${ret}")
	
	eval $__resultvar="'$tmp'"
	
	return 0
}

#----------------------------------------------------------
if [ $# -lt 2 ]; then
	print_err
	exit 1
fi

flag=$1
name=$2
ret_info=""

#echodebug "start time [$(date +"%Y%m%d %H%M%S")]"
case "${flag}" in
	"0")
		get_thread_info boar agent server ret_info
		is_suc "CURLINE[$LINENO], get_thread_info boar agent server"
	;;
	
	"1")
		shell_name=$(basename $0)
		#echo "shell_name[${shell_name}]"
		arr_pid=($(ps -ef |grep boar agent server |grep -v "grep\|${shell_name}" |awk '{print $2}'))
		is_suc "ps -ef get pid"
		if [ ${#arr_pid[@]} -ne 1 ]; then
			echoinfo "CURLINE[$LINENO], 通过name[boar agent server]获取进程id不唯一, arr_pid[${arr_pid[*]}]"
			echoerr "key[boar agent server]获取进程不唯一"
			exit 1
		fi
	
		get_thread_info ${arr_pid[0]} ret_info
		is_suc "CURLINE[$LINENO], get_thread_info ${arr_pid[0]}"
	;;
	
	*)
		echoinfo "输入[获取java进程方式], [${flag}]错误"
		print_err
		exit 1
	;;
esac
#echodebug "end time [$(date +"%Y%m%d %H%M%S")]"

echo "${ret_info}"


exit 0

